package com.wpml.netty.nio.time;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

public class MultiTimeServer implements Runnable{

    Selector selector;
    ServerSocketChannel server;
    volatile boolean stop;

    public MultiTimeServer(int port) {
        try {
            selector = Selector.open();
            server = ServerSocketChannel.open();
            server.bind(new InetSocketAddress(port));
            server.configureBlocking(false);

            server.register(selector, SelectionKey.OP_ACCEPT);

            System.out.println("The time server is start in port : " + port);

        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void stop() {
        this.stop = true;
    }

    @Override
    public void run() {
        while (!stop) {
            try {
                int num = selector.select();
                if (num > 0) {
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        try {
                            handleInput(key);
                        } catch (Exception e) {
                            if (key != null) {
                                key.cancel();
                                if (key.channel() != null) {
                                    key.channel().close();
                                }
                            }
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            /*if (selector != null) {
                try {
                    selector.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }*/
        }
    }

    private void handleInput(SelectionKey key) {
        try {
            if (key.isValid()) {
                if (key.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel client = server.accept();
                    client.configureBlocking(false);

                    client.register(selector, SelectionKey.OP_READ);
                }
                if (key.isReadable()) {
                    SocketChannel client = (SocketChannel) key.channel();
                    ByteBuffer buf = ByteBuffer.allocate(1024);
                    int read = client.read(buf);
                    if (read > 0) {
                        buf.flip();
                        byte[] bytes = new byte[buf.remaining()];
                        buf.get(bytes);

                        String body = new String(bytes);
                        System.out.println("接收到的数据 " + body);

                        String currentTime =
                                "QUERY TIME ORDER".equalsIgnoreCase(body) ? "return " + new Date().toString() :
                                "BAD ORDER";

                        doWrite(client, currentTime);
                    }

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            key.cancel();
            try {
                key.channel().close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    private void doWrite(SocketChannel client, String msg) throws IOException {
        byte[] bytes = msg.getBytes();
        ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
        byteBuffer.put(bytes);
        byteBuffer.flip();
        client.write(byteBuffer);

        /*if (!byteBuffer.hasRemaining()) {
            this.stop = true; // 发送完数据停止服务
        }*/
    }
}
